﻿using System;
using System.Windows;
using System.ServiceModel;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using System.Collections.Generic;
using System.Windows.Controls;
using TFSBuddy.IBuddy;
using TFSBuddy.Settings;
using System.ServiceModel.Description;
using System.Linq;
namespace TFSBuddy

{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Uri serviceUri=new Uri(String.Format("http://{0}:{1}", System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).HostName, Settings.Settings.Default.ServicePort));
            Uri[] baseAddresses = new Uri[] {serviceUri };
            Settings.Settings.Default.ServiceUrl=serviceUri.ToString();

            var tfsNotifierService = new TFSNotifierService(this);
            var sh = new System.ServiceModel.ServiceHost(tfsNotifierService, baseAddresses);

            var smb = sh.Description.Behaviors.Find<ServiceMetadataBehavior>();   
            if(smb ==null)
            {
                smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;  
                sh.Description.Behaviors.Add(smb);
            }
            else  
            {
                smb.HttpGetEnabled = true;  
            }

            //setup the debug behaviour
            var sdb = sh.Description.Behaviors.Find<ServiceDebugBehavior>();
            if(sdb ==null)
            {
                sdb = new ServiceDebugBehavior();
                sdb.IncludeExceptionDetailInFaults = true;
                
                sh.Description.Behaviors.Add(sdb); 
            }
            else
            {
                sdb.IncludeExceptionDetailInFaults = true;
            }

            //Endpoints
            sh.Description.Endpoints.Clear();

            try
            {
                sh.AddServiceEndpoint(typeof(ITFSNotifierService), GetSecureWSHttpBinding(), "");
                sh.AddServiceEndpoint(typeof(IMetadataExchange), GetSecureWSHttpBinding(), "mex");
                sh.Open();
            }
            catch (Exception ex)
            { 
            }
            

            //Load action tab
            comboboxHeadEffect.ItemsSource=Enum.GetNames(typeof(iBuddyHeadEffects));
            comboboxBodyEffect.ItemsSource = Enum.GetNames(typeof(iBuddyBodyEffects));
            comboboxDurationEffect.ItemsSource = Enum.GetNames(typeof(iBuddyDurationEffects));
            comboboxHeartEffect.ItemsSource = Enum.GetNames(typeof(iBuddyHeartEffects));
            comboboxWingEffect.ItemsSource = Enum.GetNames(typeof(iBuddyWingEffects));
            comboboxEvent.ItemsSource = Enum.GetNames(typeof(EventTypes));
            dropdownEventtypes.ItemsSource = Enum.GetNames(typeof(EventTypes));
        }

        private WSHttpBinding GetSecureWSHttpBinding()
        {
            var binding = new WSHttpBinding(SecurityMode.None);
            binding.MaxReceivedMessageSize = 655360;
            binding.ReaderQuotas.MaxStringContentLength = 655360;
            binding.ReaderQuotas.MaxArrayLength = 655360;
            binding.UseDefaultWebProxy = false;
            return binding;
        }

        private void showMessage(string message)
        {
            textblockMessage.Text = message;
        }

        private bool connectToTFSAndLoadData()
        {
            try
            {
                LoadSubcriptions();
                textblockMessage.Text = "";
                return true;
            }
            catch (Microsoft.TeamFoundation.TeamFoundationServerException ex)
            {
                showMessage(ex.Message);
                return false;
            }
        }


        private void buttonSave_Click(object sender, RoutedEventArgs e)
        {
            Settings.Settings.Default.EventActionFilters = (EventActionFilterList)comboboxAction.ItemsSource;
            Settings.Settings.Default.Save();
        }

        #region Subscriptions tab

        private void LoadSubcriptions()
        {
            listviewSubscriptions.ItemsSource = GetNotificationSubscriptions();
        }

        public IEnumerable<Subscription> GetNotificationSubscriptions()
        {
            using (TfsTeamProjectCollection server = new TfsTeamProjectCollection(new Uri(Settings.Settings.Default.TFSUrl)))
            {
                IEventService eventEndpoint = (IEventService)server.GetService(typeof(IEventService));
                var serversubscriptions = eventEndpoint.GetEventSubscriptions(Settings.Settings.Default.TFSUserID);
                foreach (var serversubscription in serversubscriptions)
                {
                    if (serversubscription.DeliveryPreference.Address == Settings.Settings.Default.ServiceUrl)
                    {
                        yield return serversubscription;
                    }
                }
            }
        }

        private void AddNotificationSubscription(IEventService eventEndpoint, EventTypes eventType, string filter)
        {
            try
            {
                DeliveryPreference delPrev = new DeliveryPreference
                {
                    Type = DeliveryType.Soap,
                    Schedule = DeliverySchedule.Immediate,
                    Address = Settings.Settings.Default.ServiceUrl
                };
                eventEndpoint.SubscribeEvent(Settings.Settings.Default.TFSUserID, eventType.ToString(), filter, delPrev);
            }
            catch (TeamFoundationServiceException ex)
            {
                textblockMessage.Text = ex.Message;
            }
        }

        
        private void buttonAddSubscription_Click(object sender, RoutedEventArgs e)
        {
            if (dropdownEventtypes.SelectedItem != null)
            {
                using (TfsTeamProjectCollection server = new TfsTeamProjectCollection(new Uri(Settings.Settings.Default.TFSUrl)))
                {
                    IEventService eventEndpoint = (IEventService)server.GetService(typeof(IEventService));
                    AddNotificationSubscription(eventEndpoint, (EventTypes)Enum.Parse(typeof(EventTypes), dropdownEventtypes.SelectedItem.ToString()), "");
                }
            }
            LoadSubcriptions();
        }

        private void buttonRemoveSubscription_Click(object sender, RoutedEventArgs e)
        {
            if (listviewSubscriptions.SelectedItem != null)
            {
                using (TfsTeamProjectCollection server = new TfsTeamProjectCollection(new Uri(Settings.Settings.Default.TFSUrl)))
                {
                    IEventService eventEndpoint = (IEventService)server.GetService(typeof(IEventService));
                    eventEndpoint.UnsubscribeEvent(((Subscription)listviewSubscriptions.SelectedItem).ID);
                }
                LoadSubcriptions();
            }
        }
        #endregion

        #region Events tab

        private void buttonNewEventAction_Click(object sender, RoutedEventArgs e)
        {
            if (Settings.Settings.Default.EventActionFilters == null)
            {
                Settings.Settings.Default.EventActionFilters = new EventActionFilterList();
            }
            var newEventActionFilter = new EventActionFilter() { Name = "New event action",Repeat=1 };
            Settings.Settings.Default.EventActionFilters.Add(newEventActionFilter);
            ReloadEventActions();
            comboboxAction.SelectedItem = newEventActionFilter;
        }

        public void ReloadEventActions()
        {
            comboboxAction.ItemsSource = Settings.Settings.Default.EventActionFilters;
        }


        public void ReloadStates()
        {
            if (comboboxAction.SelectedItem != null)
            {
                listviewStates.ItemsSource = (iBuddyStateList)((EventActionFilter)comboboxAction.SelectedItem).States;
            }
        }


        private void buttonAddEffect_Click(object sender, RoutedEventArgs e)
        {
            if (comboboxAction.SelectedItem != null)
            {
                var ea = ((EventActionFilter)comboboxAction.SelectedItem);
                if (ea.States == null)
                {
                    ea.States = new iBuddyStateList();
                }
                ea.States.Add(new iBuddyState()
                {
                    BodyEffect = (iBuddyBodyEffects)Enum.Parse(typeof(iBuddyBodyEffects), comboboxBodyEffect.SelectedValue.ToString()),
                    DurationEffect = (iBuddyDurationEffects)Enum.Parse(typeof(iBuddyDurationEffects), comboboxDurationEffect.SelectedValue.ToString()),
                    HeadEffect = (iBuddyHeadEffects)Enum.Parse(typeof(iBuddyHeadEffects), comboboxHeadEffect.SelectedValue.ToString()),
                    HeartEffect = (iBuddyHeartEffects)Enum.Parse(typeof(iBuddyHeartEffects), comboboxHeartEffect.SelectedValue.ToString()),
                    WingEffect = (iBuddyWingEffects)Enum.Parse(typeof(iBuddyWingEffects), comboboxWingEffect.SelectedValue.ToString())
                });
                ReloadStates();
            }
        }

        private void buttonRemoveEffect_Click(object sender, RoutedEventArgs e)
        {
            if (comboboxAction.SelectedItem != null && listviewStates.SelectedItem != null)
            {
                var ea = ((EventActionFilter)comboboxAction.SelectedItem);
                ea.States.Remove((iBuddyState)listviewStates.SelectedItem);
            }
        }

        private void comboboxEvent_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboboxAction.SelectedItem != null)
            {
                ((EventActionFilter)comboboxAction.SelectedItem).EventType = (EventTypes)Enum.Parse(typeof(EventTypes), comboboxEvent.SelectedItem.ToString());
            }
        }

        private void comboboxAction_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (comboboxAction.SelectedItem != null)
            {
                comboboxEvent.SelectedItem = ((EventActionFilter)comboboxAction.SelectedItem).EventType.ToString();
            }
        }

        private void buttonTest_Click(object sender, RoutedEventArgs e)
        {
            if (comboboxAction.SelectedItem != null)
            {
                var ea = ((EventActionFilter)comboboxAction.SelectedItem);
               
                IBuddyHelper.ActivateIBuddyEvent(ea.States,Convert.ToInt32(textboxRepeat.Text), IBuddyHelper.GetBuddyList(),this);
            }
        }

        #endregion

        private void buttonConnect_Click(object sender, RoutedEventArgs e)
        {
            var connectionSucceded = connectToTFSAndLoadData();
            Settings.Settings.Default.ConnectionTested = connectionSucceded;
            tabActions.IsEnabled = connectionSucceded;
            tabSubscriptions.IsEnabled = connectionSucceded;
            if (connectionSucceded)
            {
                listviewSubscriptions.IsEnabled = true;
                dropdownEventtypes.IsEnabled = true;
                buttonAddSubscription.IsEnabled = true;
                buttonRemoveSubscription.IsEnabled = true;
                showMessage("Connection Succeeded");
            }
        }
    }
}
